package ctrl

import (
	"encoding/json"
	"errors"
	"fmt"
	"gin_zebra/app/dao"
	"gin_zebra/app/dto"
	"gin_zebra/app/middleware"
	"gin_zebra/public"
	"gitee.com/xiedongji/go-core/lib"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

type UserController struct{}

func UserRegister(router *gin.RouterGroup) {
	ctrl := &UserController{}
	router.GET("/info", ctrl.Info)
	router.POST("/mod", ctrl.Mod)
	router.POST("/modpwd", ctrl.ModPwd)
	router.GET("/logout", ctrl.Logout)
}

func (ctrl *UserController) Info(ctx *gin.Context) {
	fmt.Println("执行到这里")
	sess := sessions.Default(ctx)
	sessInfo := sess.Get(public.SessionUserKey)

	userSession := &dto.UserSession{}
	if err := json.Unmarshal([]byte(fmt.Sprint(sessInfo)), userSession); err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	user := &dao.User{}
	user, err := user.Find(ctx, lib.GORMDefaultPool, &dao.User{Id: userSession.Id})
	if err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	middleware.ResponseSuccess(ctx, user)
}

func (ctrl *UserController) Mod(ctx *gin.Context) {
	ctx.JSON(200, gin.H{
		"message": "mod",
	})
}

func (ctrl *UserController) ModPwd(ctx *gin.Context) {
	ctx.JSON(200, gin.H{
		"message": "ModPwd",
	})
}

func (ctrl *UserController) Logout(ctx *gin.Context) {
	sess := sessions.Default(ctx)
	sess.Delete(public.SessionUserKey)
	sess.Save()

	middleware.ResponseError(ctx, errors.New("test"))

	middleware.ResponseSuccess(ctx, "安全退出")
}
